<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>学知鸟</title>
		<link rel="shortcut icon" href="../../share/img/logo.png">
		<link rel="stylesheet" href="../../share/css/main.css">
		<script src="../../share/js/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body class="p-10">
		<h1>闭包</h1>
		<div class="row">
			<div class="col-1">
				<section>
					<h3>概念</h3>
					<ul class="plist">
						<li class="title">背景:</li>
						<li>JS中变量根据作用域可分为全局变量和局部变量。</li>
						<li>在函数外部声明的变量是全局变量，函数内部声明的变量是局部变量。</li>
						<li>全局变量可在程序的任意部分访问，包括函数外部和各函数内。</li>
						<li>局部变量只可在声明变量的函数内部访问，函数外和其它函数无法访问。</li>
						<li></li>
					</ul>
				</section>
			</div>
			<div class="col-1">
				<section>
					<h3>语法</h3>
					<div id="log">输出日志</div>
					<div>
						<pre id="code"></pre>
					</div>
				</section>
			</div>
			<div class="col-1">
				<section>
					<h3>示例: </h3>
					<button onclick="test01();">方法中访问全局变量</button>
					<button onclick="test02();">方法中访问局部变量</button>
					<button onclick="test03();">局部变量与全局变量同名</button>
					<br>
					<button onclick="testAdd();">闭包内自增</button>
					<button onclick="testMinus();">闭包内自减</button>
				</section>
			</div>
		</div>
		<script type="text/javascript">
			var name1 = "Tom";

			function test01() {
				log("全局变量 name: " + name1);
			}

			function test02() {
				var name2 = "Jack";
				log("局部变量 name2: " + name2);
			}

			function test03() {
				log("局部变量 name: " + name1);
				var name1 = "Lucy";
				log("局部变量 name: " + name1);
				showCode(arguments.callee);
			}

			function test04() {
				var count = 0;

				function add() {
					log(count);
					return count++;
				}

				function minus() {
					log(count);
					return count--;
				}
				return {
					add,
					minus
				};
			}

			var result04 = test04();

			function testAdd() {
				result04.add();
				showCode(result04.add);
			}

			function testMinus() {
				result04.minus();
				showCode(result04.minus);
			}

			function log(text, append) {
				console.log(text);
				$("#log").text(text);
			}

			function showCode(text, append) {
				$("#code").text("" + text);
			}
		</script>
	</body>
</html>
